package modulos;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.Border;

import auxiliary.Constants;
import auxiliary.Database;

public class PanelMaquinaria extends JPanel implements ActionListener {

	ArrayList<ArrayList<String>> listOfMaquinarias;
	Database db;
	ArrayList<JRadioButton> radiobuttons;
	ButtonGroup group;
	JPanel radioPanel;
	int currentButton;
	JTable jt;
	TableModelMaquinaria mtm;
	PanelMaquinaria panel;
	ImageIcon imageicon,redicon,greenicon,add,delete,modify;
	JLabel imagelabel;

	public PanelMaquinaria() {
		panel = this;
		db = new Database();
		
		listOfMaquinarias = db.retrieveMaquinaria();
		currentButton = 0;
		String[] strArray = new String[listOfMaquinarias.size()];

		mtm = new TableModelMaquinaria();
		jt = new JTable(mtm);
		updateTable();

		URL imgURL = ClassLoader.getSystemResource("images/back.png");
		Image image = Toolkit.getDefaultToolkit().getImage(imgURL);

		// String dir = System.getProperty("user.dir");
		imageicon = new ImageIcon(image);
		imagelabel = new JLabel(imageicon);
	
		imgURL = ClassLoader.getSystemResource("images/red.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);
		
		redicon = new ImageIcon(image);
		
		Image img = redicon.getImage();  
		Image newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		redicon = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/green.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		greenicon = new ImageIcon(image);
		
		img = greenicon.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		greenicon = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/add.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		add = new ImageIcon(image);
		
		img = add.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		add = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/delete.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		delete = new ImageIcon(image);
		
		img = delete.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		delete = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/modify.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		modify = new ImageIcon(image);
		
		img = modify.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		modify = new ImageIcon(newimg);

		radiobuttons = new ArrayList<JRadioButton>();
		for (Integer i = 0; i < listOfMaquinarias.size(); i++) {
			radiobuttons.add(new JRadioButton());
			radiobuttons.get(i).setSize(20, 20);
			radiobuttons.get(i).setActionCommand(i.toString());
			radiobuttons.get(i).addActionListener(this);
			radiobuttons.get(0).setSelected(true);
		}

		group = new ButtonGroup();

		radioPanel = new JPanel();
		radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));

		radioPanel.add(Box.createRigidArea(new Dimension(10, 30)));
		
		for (int i = 0; i < listOfMaquinarias.size(); i++) {

			group.add(radiobuttons.get(i));
			radioPanel.add(radiobuttons.get(i));
			radioPanel.add(Box.createRigidArea(new Dimension(4,4)));

		}

		jt.setEnabled(false);
		jt.setRowHeight(22);
		jt.getTableHeader().setReorderingAllowed(false);
		jt.getTableHeader().setFont(new Font("Dialog", Font.BOLD, 14));
		//jt.getTableHeader().setResizingAllowed(false);

		JScrollPane jsp = new JScrollPane(jt);
		jsp.setPreferredSize(new Dimension(900, 475));

		JButton addbutton = new JButton("Agregar",add);
		addbutton.setActionCommand(Constants.MAQUINARIA_AGREGAR);
		addbutton.addActionListener(this);

		JButton removebutton = new JButton("Eliminar",delete);
		removebutton.setActionCommand(Constants.MAQUINARIA_ELIMINAR);
		removebutton.addActionListener(this);

		JButton modifybutton = new JButton("Modificar",modify);
		modifybutton.setActionCommand(Constants.MAQUINARIA_MODIFICAR);
		modifybutton.addActionListener(this);

		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
		// JPanel bottomPanel = new JPanel(new BorderLayout());
		JPanel topPanel = new JPanel(new BorderLayout());

		buttonPanel.add(Box.createHorizontalGlue());
		buttonPanel.add(addbutton, BorderLayout.WEST);
		buttonPanel.add(modifybutton, BorderLayout.CENTER);
		buttonPanel.add(removebutton, BorderLayout.EAST);
		buttonPanel.add(Box.createHorizontalGlue());
		buttonPanel.add(imagelabel, BorderLayout.EAST);

		topPanel.add(jsp, BorderLayout.CENTER);
		topPanel.add(radioPanel, BorderLayout.WEST);

		// bottomPanel.add(buttonPanel,BorderLayout.CENTER);

		this.setLayout(new BorderLayout());
		this.add(topPanel, BorderLayout.NORTH);
		this.add(buttonPanel, BorderLayout.SOUTH);

		this.setVisible(true);

	}

	private void setColumnWidth() {

		jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		jt.getColumnModel().getColumn(0).setPreferredWidth(124);
		jt.getColumnModel().getColumn(1).setPreferredWidth(50);
		jt.getColumnModel().getColumn(2).setPreferredWidth(50);
		jt.getColumnModel().getColumn(3).setPreferredWidth(50);
		jt.getColumnModel().getColumn(4).setPreferredWidth(40);
		jt.getColumnModel().getColumn(5).setPreferredWidth(20);
		jt.getColumnModel().getColumn(6).setPreferredWidth(655);

	}

	void addRadioButton() {
		Integer buttonindex = listOfMaquinarias.size() - 1;

		radiobuttons.add(new JRadioButton());
		radiobuttons.get(buttonindex).setSize(23, 23);
		radiobuttons.get(buttonindex).setActionCommand(buttonindex.toString());
		radiobuttons.get(buttonindex).addActionListener(this);

		group.add(radiobuttons.get(buttonindex));
		//radioPanel.add(radiobuttons.get(buttonindex));
		//radioPanel.add(Box.createRigidArea(new Dimension(4,4)));
		
		radioPanel.removeAll();
		radioPanel.add(Box.createRigidArea(new Dimension(10, 30)));
		
		for (int i = 0; i < radiobuttons.size(); i++) {

			radioPanel.add(radiobuttons.get(i));
			radioPanel.add(Box.createRigidArea(new Dimension(4,4)));

		}

		for (Integer i = 0; i < radiobuttons.size(); i++) {
			radiobuttons.get(i).setActionCommand(i.toString());
		}

		if (radiobuttons.size() > 0)
			radiobuttons.get(0).setSelected(true);
		currentButton = 0;
	}

	void deleteRadioButton(int button) {
		final int curr = button;

		
		group.remove(radiobuttons.get(curr));
		radiobuttons.remove(curr);
		
		radioPanel.removeAll();
		radioPanel.add(Box.createRigidArea(new Dimension(10, 30)));
		
		for (int i = 0; i < radiobuttons.size(); i++) {

			radioPanel.add(radiobuttons.get(i));
			radioPanel.add(Box.createRigidArea(new Dimension(4,4)));

		}

		for (Integer i = 0; i < radiobuttons.size(); i++) {
			radiobuttons.get(i).setActionCommand(i.toString());
		}
		if (radiobuttons.size() > 0)
			radiobuttons.get(0).setSelected(true);
		currentButton = 0;
	}

	public void actionPerformed(ActionEvent e) {
		String command = e.getActionCommand();
		if (command == Constants.MAQUINARIA_AGREGAR) {
			String[] labels = { "Modelo", "Produccion", "Llenado", "Loteado",
					"Capacidad", "Funcionarios" };
			int[] widths = { 15, 9, 9, 9, 9, 9 };
			String[] descs = { "Modelo", "Produccion", "Llenado", "Loteado",
					"Capacidad", "Funcionarios" };

			AgregarMaquinaria agregar = new AgregarMaquinaria(jt, labels,
					widths, descs, Constants.getParentFrame(this));
			// agregar.setVisible(true);

		} else if (command == Constants.MAQUINARIA_ELIMINAR) {

			String[][] allvalues = Constants
					.arrayListToString(listOfMaquinarias);

			List<String> list = new ArrayList<String>(Arrays
					.asList(allvalues[currentButton]));
			String[] values = list.toArray(new String[0]);

			boolean deleted = db.deleteMaquinaria(values);

			if (deleted) {
				listOfMaquinarias = db.retrieveMaquinaria();

				updateTable();
				deleteRadioButton(currentButton);
				radioPanel.revalidate();
				radioPanel.repaint();
			} else {
				JOptionPane
						.showMessageDialog(
								new JFrame(),
								"Error: Borre o Modifique primero items de funcionario/producto que referencian maquinaria",
								"Mensaje de Error", JOptionPane.ERROR_MESSAGE);
			}

			// panel.revalidate();
			// panel.repaint();

		} else if (command == Constants.MAQUINARIA_MODIFICAR) {

			String[][] allvalues = Constants
					.arrayListToString(listOfMaquinarias);

			String[] labels = { "Modelo", "Produccion", "Llenado", "Loteado",
					"Capacidad", "Funcionarios" };
			int[] widths = { 15, 9, 9, 9, 9, 9 };
			String[] descs = { "Modelo", "Produccion", "Llenado", "Loteado",
					"Capacidad", "Funcionarios" };

			List<String> list = new ArrayList<String>(Arrays
					.asList(allvalues[currentButton]));
			String[] values = list.toArray(new String[0]);

			ModificarMaquinaria agregar = new ModificarMaquinaria(labels,
					widths, descs, values, Constants.getParentFrame(this));
		} else {
			currentButton = Integer.valueOf(e.getActionCommand());
		}
	}

	public void updateTable() {
		mtm.updateTable();
		setColumnWidth();
	}

	public class ModificarMaquinaria extends JDialog implements ActionListener {

		Container contentPane;
		JPanel form;
		JTextField[] fields;
		String hiddenfield;
		// Database db;
		ModificarMaquinaria modificarFrame;
		JCheckBox boxes[];
		JComboBox numfuncionarios;

		public ModificarMaquinaria(final String[] labels, final int[] widths,
				final String[] tips, final String[] values, JFrame parent) {

			super(parent, "Agregar Maquinaria",
					Dialog.ModalityType.DOCUMENT_MODAL);

			// db = new Database();
			modificarFrame = this;
			contentPane = getContentPane();

			boxes = new JCheckBox[3];
			// form = new JPanel(new BorderLayout());

			Border grayborder = BorderFactory
					.createLineBorder(Color.LIGHT_GRAY);

			Border loweredbevel = BorderFactory.createLoweredBevelBorder();

			Border border = BorderFactory.createTitledBorder(loweredbevel,
					"Informacion de Maquinaria");

			JPanel form = new JPanel();
			form.setLayout(new BoxLayout(form, BoxLayout.X_AXIS));

			JPanel buttonPanel = new JPanel();

			JPanel labelPanel = new JPanel(new GridLayout(labels.length, 1));
			JPanel fieldPanel = new JPanel(new GridLayout(labels.length, 1));

			form.add(labelPanel);
			form.add(Box.createRigidArea(new Dimension(10, 25)));
			form.add(fieldPanel);

			form.setBorder(border);
			fieldPanel.setBorder(grayborder);

			fields = new JTextField[labels.length];

			hiddenfield = values[0];
			for (int i = 0; i < labels.length; i++) {
				fields[i] = new JTextField();
				if (i < tips.length)
					fields[i].setToolTipText(tips[i]);
				if (i < widths.length)
					fields[i].setColumns(widths[i]);
				fields[i].setText(values[i + 1]);

				JLabel lab = new JLabel(labels[i], JLabel.RIGHT);
				lab.setLabelFor(fields[i]);
				labelPanel.add(lab);
				JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
				// if(i==1 || i==2 || i==3) {
				// boxes[i-1] = new JCheckBox();
				if (i == 1 || i == 2 || i == 3) {
					boxes[i - 1] = new JCheckBox();
					p.add(boxes[i - 1]);
					if (values[i + 1].equals("Si")) {
						boxes[i - 1].setSelected(true);
					}
				} else if (i == 5) {
					numfuncionarios = new JComboBox(new String[] { "1", "2",
							"3", "4", "5" });
					numfuncionarios.setSelectedIndex(Integer
							.valueOf(values[i + 1]) - 1);
					p.add(numfuncionarios);
				} else {
					p.add(fields[i]);
				}
				// }
				fieldPanel.add(p);
			}

			JPanel confirmarbuttonpanel = new JPanel(new GridBagLayout());
			JButton cancelarbutton = new JButton("Cancelar",redicon);
			cancelarbutton.addActionListener(this);
			cancelarbutton.setActionCommand(Constants.MAQUINARIA_CANCELAR_MODIFICAR_CONFIRMACION);
			
			GridBagConstraints c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 0;
			c.gridy = 0;
			
			confirmarbuttonpanel.add(cancelarbutton, c);
			
			
			JButton confirmarbutton = new JButton("Confirmar",greenicon);
			confirmarbutton.addActionListener(this);
			confirmarbutton.setActionCommand(Constants.MAQUINARIA_MODIFICAR_CONFIRMACION);
			
			c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 1;
			c.gridy = 0;
			
			confirmarbuttonpanel.add(confirmarbutton, c);

			contentPane.add(form, BorderLayout.NORTH);
			contentPane.add(confirmarbuttonpanel, BorderLayout.SOUTH);
			pack();

			setVisible(true);

		}

		public void actionPerformed(ActionEvent e) {

			String values[];

			String command = e.getActionCommand();
			if (command == Constants.MAQUINARIA_MODIFICAR_CONFIRMACION) {

				boolean validnumber = true;

				try {
					Integer.parseInt(fields[4].getText());
				} catch (Exception exp) {

					validnumber = false;
				}

				if (validnumber) {
					values = new String[fields.length + 1];
					values[0] = hiddenfield;

					for (int i = 0; i < fields.length; i++) {
						if (i == 1 || i == 2 || i == 3) {
							System.out.println("i" + i + " boxes"
									+ boxes[i - 1].isSelected());
							if (boxes[i - 1].isSelected()) {
								values[i + 1] = "1";
							} else {
								values[i + 1] = "0";
							}
						} else if (i == 5) {
							values[i + 1] = (String) numfuncionarios
									.getSelectedItem();
						} else {
							values[i + 1] = fields[i].getText();
						}
					}


					db.modifyMaquinaria(values);
					listOfMaquinarias = db.retrieveMaquinaria();
					updateTable();
					modificarFrame.dispose();
				} else {
					JOptionPane
							.showMessageDialog(
									new JFrame(),
									"Se encontraron los siguientes errores al verificar formulario:"
											+ "\n\n"
											+ (validnumber ? ""
													: "- Ingrese un numero valido para capacidad en litros\n"),
									"Mensaje de Error",
									JOptionPane.ERROR_MESSAGE);
				}

			} else if(command.equals(Constants.MAQUINARIA_CANCELAR_MODIFICAR_CONFIRMACION)){
				modificarFrame.dispose();
			}
		}
	}

	public class AgregarMaquinaria extends JDialog implements ActionListener {

		Container contentPane;
		JPanel form;
		JTextField[] fields;
		Database db;
		// FuncionarioPanel panel;
		AgregarMaquinaria agregarFrame;
		JCheckBox boxes[];
		JComboBox numfuncionarios;

		public AgregarMaquinaria(JTable jt, final String[] labels,
				final int[] widths, final String[] tips, JFrame parent) {
			super(parent, "Agregar Maquinaria",
					Dialog.ModalityType.DOCUMENT_MODAL);

			agregarFrame = this;
			//db = new Database();
			contentPane = getContentPane();

			boxes = new JCheckBox[3];

			Border grayborder = BorderFactory
					.createLineBorder(Color.LIGHT_GRAY);

			Border loweredbevel = BorderFactory.createLoweredBevelBorder();

			Border border = BorderFactory.createTitledBorder(loweredbevel,
					"Informacion de Maquinaria");

			JPanel form = new JPanel();
			form.setLayout(new BoxLayout(form, BoxLayout.X_AXIS));

			JPanel buttonPanel = new JPanel();

			JPanel labelPanel = new JPanel(new GridLayout(labels.length, 1));
			JPanel fieldPanel = new JPanel(new GridLayout(labels.length, 1));

			form.add(labelPanel);
			form.add(Box.createRigidArea(new Dimension(10, 25)));
			form.add(fieldPanel);

			form.setBorder(border);
			fieldPanel.setBorder(grayborder);

			fields = new JTextField[labels.length];

			for (int i = 0; i < labels.length; i++) {
				fields[i] = new JTextField();
				if (i < tips.length)
					fields[i].setToolTipText(tips[i]);
				if (i < widths.length)
					fields[i].setColumns(widths[i]);

				JLabel lab = new JLabel(labels[i], JLabel.RIGHT);
				lab.setLabelFor(fields[i]);
				labelPanel.add(lab);
				JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
				if (i == 1 || i == 2 || i == 3) {
					boxes[i - 1] = new JCheckBox();
					p.add(boxes[i - 1]);
				} else if (i == 5) {
					numfuncionarios = new JComboBox(new String[] { "1", "2",
							"3", "4", "5" });
					p.add(numfuncionarios);
				} else {
					p.add(fields[i]);
				}

				//

				fieldPanel.add(p);
			}
			fields[4].setEnabled(false);
			boxes[0].addActionListener(this);
			boxes[0].setActionCommand(Constants.MAQUINARIA_PRODUCE);

			JPanel confirmarbuttonpanel = new JPanel(new GridBagLayout());
			JButton cancelarbutton = new JButton("Cancelar",redicon);
			cancelarbutton.addActionListener(this);
			cancelarbutton.setActionCommand(Constants.MAQUINARIA_AGREGAR_CANCELAR);
			
			GridBagConstraints c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 0;
			c.gridy = 0;
			
			confirmarbuttonpanel.add(cancelarbutton, c);
			
			
			JButton confirmarbutton = new JButton("Confirmar",greenicon);
			confirmarbutton.addActionListener(this);
			confirmarbutton.setActionCommand(Constants.MAQUINARIA_AGREGAR_CONFIRMACION);
			
			c = new GridBagConstraints();

			c.insets = new Insets(15,0,15,0);
			c.weightx = 0.25;
			c.anchor = GridBagConstraints.CENTER;
			c.gridx = 1;
			c.gridy = 0;
			
			confirmarbuttonpanel.add(confirmarbutton, c);

			contentPane.add(form, BorderLayout.NORTH);
			contentPane.add(confirmarbuttonpanel, BorderLayout.SOUTH);
			pack();

			setVisible(true);
		}

		public void actionPerformed(ActionEvent e) {
			ArrayList<String> maquinariaData = new ArrayList<String>();

			String command = e.getActionCommand();
			if (command == Constants.MAQUINARIA_AGREGAR_CONFIRMACION) {

				boolean validnumber = true;

				if (boxes[0].isSelected()) {
					try {
						Integer.parseInt(fields[4].getText());
						// validnumber = true;
					} catch (Exception exp) {

						validnumber = false;
					}
				}

				if (validnumber) {
					for (int i = 0; i < fields.length; i++) {
						if (i == 1 || i == 2 || i == 3) {
							if (boxes[i - 1].isSelected()) {
								maquinariaData.add("1");
							} else {
								maquinariaData.add("0");
							}
						} else if (i == 5) {
							maquinariaData.add(String.valueOf(numfuncionarios
									.getSelectedIndex() + 1));
						} else if (i == 4) {
							if (boxes[0].isSelected()) {
								maquinariaData.add(fields[i].getText());
							} else
								maquinariaData.add("0");
						} else {
							maquinariaData.add(fields[i].getText());
						}
					}

					db.insertMaquinaria(maquinariaData);
					listOfMaquinarias = db.retrieveMaquinaria();

					updateTable();
					addRadioButton();
					radioPanel.revalidate();

					agregarFrame.dispose();

				} else {
					JOptionPane
							.showMessageDialog(
									new JFrame(),
									"Se encontraron los siguientes errores al verificar formulario:"
											+ "\n\n"
											+ (validnumber ? ""
													: "- Ingrese un numero valido para capacidad en litros\n"),
									"Mensaje de Error",
									JOptionPane.ERROR_MESSAGE);
				}

			} else if (command == Constants.MAQUINARIA_AGREGAR_CANCELAR) {
				agregarFrame.dispose();
			}
			else if (command == Constants.MAQUINARIA_PRODUCE) {
				if (boxes[0].isSelected()) {
					// fields[4].setText("");
					fields[4].setEnabled(true);
				} else {
					fields[4].setEnabled(false);
					fields[4].setText("");
				}

			} else {

			}
		}
	}
}
